const express = require('express');
const { Sequelize , DataTypes } = require('sequelize');
const bodyParser = require('body-parser');
const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: './index.sqlite'
});
async function initDB(){
    
try {
    await sequelize.authenticate();
    console.log('Connection has been established successfully.');
  } catch (error) {
    console.error('Unable to connect to the database:', error);
  }
  
}

const Item = sequelize.define('Item', {
  // 在这里定义模型属性
  id: {
    type: DataTypes.INTEGER,
    primaryKey:true,
    autoIncrement:true,
  },
  content:{
    type: DataTypes.STRING,
    allowNull: false,
  }
}, {
  // 这是其他模型参数
});
initDB();
const app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded())
app.listen(3000,()=>{
    console.log('服务已启动');
})

app.get('/list',(req,res)=>{
    Item.findAll().then(data=>{
        res.json(data)
    })
})
app.get('/reset',async (req,res)=>{
    await sequelize.sync({force:true})
    res.json({
        message:'数据库初始化成功'
    })
})
app.post('/save', (req,res)=>{
    Item.create({
        content:req.body.content
    }).then(()=>{
        res.json({
            message:'保存成功'
        })
    })
})
app.get('/delete',(req,res)=>{
    const id = req.query.id
    Item.destroy({
        where:{
            id
        }
    }).then(()=>{
        res.json({
            message:'删除成功'
        })
    })

})